import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.css']
})

export class PageComponent implements OnInit, OnChanges {
  
  @Output() loadData = new EventEmitter();
  @Input() currentPage:number;
  @Input() showRecord:number;
  @Input() totalRecord:number;
  private totalPage:number;
  private pages: number[];
  
  constructor() { }
  
  ngOnInit() { }

  ngOnChanges(changes: SimpleChanges) {
    this.pages = [];
    if(this.totalRecord > 0) {
      this.totalPage = Math.ceil(this.totalRecord / this.showRecord);
      let startPage = this.currentPage-3<1 ? 1 : this.currentPage-3;
      let endPage = startPage+6>this.totalPage ? this.totalPage : startPage+6;
      startPage = endPage-6>0 ? endPage-6 : 1;
      for (let index = startPage; index <= endPage; index++) {
        this.pages.push(index);
      }
    } else {
      this.totalPage = 1;
    }
  }

  queryData(pageNumber) {
    if(pageNumber == 'prev') {
      pageNumber = this.currentPage-1<1 ? 1 : this.currentPage-1;
    } else if(pageNumber == 'next') {
      pageNumber = this.currentPage+1>this.totalPage ? this.totalPage : this.currentPage+1;
    }
    if(pageNumber != this.currentPage) {
      this.loadData.emit(pageNumber);
    }
  }
}
